## DEPRECIATED
## This is no longer needed as django automatically hears
## updates from paypal and marks things as paid for via
## The IPN (Instant Payment Notification) interface of Paypal.
## See "endpoint" in urls.py

# Paypal wranging
# This sets the 'paid' field of regrecords in the sqlite database to true for
# psdids found in the paypal transaction history.

# THE STEPS:
# Download the transaction history as a csv file from Paypal
# Put the file into the psd directory
# Run this script

if ( length( grep( "Rs$", getwd(), perl=TRUE ) ) > 0 ) {
  setwd( ".." )
}

cat( "Reading from ", PAYPAL_FILENAME, "\n" )

M = read.csv( PAYPAL_FILENAME, stringsAsFactors=FALSE )
M = M[ c("Item.Title", "Gross","Fee","Net","From.Email.Address","Date") ]
#M = M[ c("Subject", "Gross","Fee","Net","From.Email.Address","Date") ]
names(M)[1] = "Item.Title"
head(M)
M = subset( M, Gross > 0 )

M$personID = gsub( "^.*\\((.*)\\)", '\\1', M$Item.Title, perl=TRUE )
M = M[-c(1)]
M$Date = as.Date( M$Date, "%m/%d/%Y" ) 

M = M[order(M$Date),]


library( "RSQLite" )
m <- dbDriver("SQLite")
con <- dbConnect(m, dbname = DATABASE_FILENAME)


qry = sprintf( "UPDATE register_regrecord SET paid=1 WHERE psdid IN ('%s');", 					paste( M$personID, collapse="', '" ) )

rs <- dbSendQuery( con, qry )
print(rs)

# pids in database
rs = dbSendQuery( con, "SELECT psdid from register_regrecord" )
pids <- fetch(rs, n = -1)
pids = pids$psdid

head(M)
nrow(M)
cat( "Gross = ", sum(M$Gross), "\nFee = ", sum(M$Fee), "\nNet = ", sum(M$Net), "\nFolks = ", sum(M$Gross) / 12, "\n" )

M$Net = NULL
M$Fee = NULL

cat( "Weird - not in database\n" )
print( M[ !(M$personID %in% pids),] )


skip = function() {


source( "polyDataRead.R" )
# folks who are in various categories
#P = read.csv( "allFolks.csv", stringsAsFactors=FALSE );
P = read.csv( "allFolks.csv", stringsAsFactors=FALSE );
rownames(P) = P$personID

ban = read.csv( "banList.csv", stringsAsFactors=FALSE )
ban = ban[c(1,4,5,6)]
	
 
P = merge( P, ban, by="personID", all=TRUE )
save.file(P, collapse.groups=TRUE, file="allRegistered.csv", 
				orderBy=c( "Paid","gender1", "lookGender1") )

cat( "allRegistered has full list of registered folks\n" )
				
#P = read.csv( "allRegistered.csv", stringsAsFactors=FALSE );
  
# print( P[ P$Paid == "", ] )
  
}

